using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using ImageScale.Properties;
using System.Diagnostics;

namespace ImageScale
{
	public partial class mainForm : Form
	{
        mainFormData _formData;

		public mainForm(string[] args)
		{
			InitializeComponent();
            BindData(args);
            InitializeControlEvents();
        }


        #region Initializing components...
        private void BindData(string[] args)
        {
            _formData = new mainFormData();
            foreach (string item in args)
            {
                if (File.Exists(item))
                {
                    _formData.Images.Add(new ImageInfo(item, _formData));
                }
            }

            formDataBindingSource.DataSource = _formData;
            imagesBindingSource.DataSource = _formData.Images;
        }

        private void InitializeControlEvents()
        {
            percentageRadio.CheckedChanged += new EventHandler(delegate(object sender, EventArgs e) { _formData.ScaleType = ScaleType.Percentage; });
            absoluteRadio.CheckedChanged += new EventHandler(delegate(object sender, EventArgs e) { _formData.ScaleType = ScaleType.Absolute; });

            saveAsRadio.CheckedChanged += new EventHandler(delegate(object sender, EventArgs e) { _formData.ScaleDestination = ScaleDestination.SaveAs; });
            clipboardRadio.CheckedChanged += new EventHandler(delegate(object sender, EventArgs e) { _formData.ScaleDestination = ScaleDestination.Clipboard; });
            overwriteRadio.CheckedChanged += new EventHandler(delegate(object sender, EventArgs e) { _formData.ScaleDestination = ScaleDestination.Overwrite; });
            folderRadio.CheckedChanged += new EventHandler(delegate(object sender, EventArgs e) { _formData.ScaleDestination = ScaleDestination.Folder; });
            ftpRadio.CheckedChanged += new EventHandler(delegate(object sender, EventArgs e) { _formData.ScaleDestination = ScaleDestination.Ftp; });
        }

        #endregion

		#region Dialog event handlers
        private void exitButton_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		private void folderButton_Click(object sender, EventArgs e)
		{
			if (getFolderDialog.ShowDialog() == DialogResult.OK)
			{
				folderTextBox.Text = getFolderDialog.SelectedPath;
			}
		}

		private void addButton_Click(object sender, EventArgs e)
		{
			if (addImageDialog.ShowDialog() == DialogResult.OK)
			{
				foreach (string file in addImageDialog.FileNames)
				{
                    imagesBindingSource.Add(new ImageInfo(file, _formData));
				}
			}
		}

		private void removeButton_Click(object sender, EventArgs e)
		{
            if (imagesBindingSource.Current != null)
            {
                imagesBindingSource.RemoveCurrent();
            }
		}

        private void imagesBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            removeButton.Enabled = imagesBindingSource.Current != null;
            scaleButton.Enabled = imagesBindingSource.List.Count > 0;
        }
        private void formDataBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            widthValue.Enabled = heightValue.Enabled = percentageValue.Enabled = false;
            switch (_formData.ScaleType)
            {
                case ScaleType.Percentage:
                    percentageValue.Enabled = true;
                    break;
                case ScaleType.Absolute:
                    widthValue.Enabled = heightValue.Enabled = true;
                    break;
            }
            saveAsLabel.Visible = folderTextBox.Enabled = folderButton.Enabled = getFtpFolderButton.Enabled = false;
            switch (_formData.ScaleDestination)
            {
                case ScaleDestination.SaveAs:
                    saveAsLabel.Visible = true;
                    break;
                case ScaleDestination.Clipboard:
                    if (clipboardRadio.Checked && imagesBindingSource.List.Count > 1)
                    {
                        MessageBox.Show(Resources.WARNING_CLIPBOARD, Resources.WARNING, MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
                    }
                    break;
                case ScaleDestination.Folder:
                    folderTextBox.Enabled = folderButton.Enabled = true;
                    break;
                case ScaleDestination.Ftp:
                    getFtpFolderButton.Enabled = true;
                    break;
            }
        }

		#endregion

        #region Scaling...
        private void scaleButton_Click(object sender, EventArgs e)
        {
            ScaleClass sc = new ScaleClass();
            switch (_formData.ScaleType)
            {
                case ScaleType.Percentage:
                    sc.PercentageValue = (int)percentageValue.Value;
                    break;
                case ScaleType.Absolute:
                    sc.Width = (int)widthValue.Value;
                    sc.Height = (int)heightValue.Value;
                    break;
            }
            switch (_formData.ScaleDestination)
            {
                case ScaleDestination.SaveAs:
                    scaleToFile(sc);
                    break;
                case ScaleDestination.Clipboard:
                    scaleToClipboard(sc);
                    break;
                case ScaleDestination.Overwrite:
                    if (MessageBox.Show(this, Properties.Resources.WARNING_OVERWRITE, Properties.Resources.WARNING,
                        MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                    {
                        scaleToSameFolder(sc);
                    }
                    break;
                case ScaleDestination.Folder:
                    if (Directory.Exists(folderTextBox.Text))
                    {
                        scaleToFolder(sc);
                    }
                    else
                    {
                        MessageBox.Show(this, Properties.Resources.DIRECTORY_NOT_EXISTS, Properties.Resources.ERROR,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    break;
                case ScaleDestination.Ftp:
                    if (!String.IsNullOrEmpty(_formData.FtpSite))
                    {
                        ScaleToFtp(sc);
                    }
                    else
                    {
                        MessageBox.Show(Resources.FTP_NOT_EXISTS, Resources.ERROR, MessageBoxButtons.OK, 
                            MessageBoxIcon.Error);
                    }
                    break;
            }
        }
        private void scaleToFile(ScaleClass sc)
        {
            try
            {
                foreach (ImageInfo item in _formData.Images)
                {
                    Bitmap outBitmap = sc.Scale(item.Picture);
                    string folderPath = Path.GetDirectoryName(item.ImagePath);
                    string filePath = Path.Combine(folderPath, item.SaveAsFileName);
                    outBitmap.Save(filePath, item.Picture.RawFormat);
                }
                MessageBox.Show(Resources.PROMPT_CLIPBOARD, Resources.MSG_COMPLETE, MessageBoxButtons.OK, 
                    MessageBoxIcon.Information);
                exitButton_Click(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.ERROR, MessageBoxButtons.OK, 
                    MessageBoxIcon.Error);
            }
        }

        private void scaleToClipboard(ScaleClass sc)
		{
            // Get current image
            if (imagesBindingSource.Current != null)
            {
                try
                {
                    ImageInfo ii = imagesBindingSource.Current as ImageInfo;
                    Bitmap outBitmap = sc.Scale(ii.Picture);
                    Clipboard.SetImage(outBitmap);
                    MessageBox.Show(Resources.PROMPT_CLIPBOARD, Resources.MSG_COMPLETE, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    exitButton_Click(null, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Resources.ERROR, MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                } 
            }
		}
		private void scaleToFolder(ScaleClass sc)
		{
            try
            {
                foreach (ImageInfo item in _formData.Images)
                {
                    Bitmap outBitmap = sc.Scale(item.Picture);
                    string fileName = Path.GetFileName(item.ImagePath);
                    string filePath = Path.Combine(folderTextBox.Text, fileName);
                    outBitmap.Save(filePath, item.Picture.RawFormat);
                }
                FolderScaleMessage message = new FolderScaleMessage();
                if (message.ShowDialog() == DialogResult.OK && message.OpenFolder)
                {
                    Process.Start(@"explorer.exe", folderTextBox.Text);
                }
                exitButton_Click(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.ERROR, MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
		}
		private void scaleToSameFolder(ScaleClass sc)
		{
            try
            {
                foreach (ImageInfo item in _formData.Images)
                {
                    Bitmap outBitmap = sc.Scale(item.Picture);
                    outBitmap.Save(item.ImagePath, item.Picture.RawFormat);
                }

                FolderScaleMessage message = new FolderScaleMessage();
                if (message.ShowDialog() == DialogResult.OK && message.OpenFolder)
                {
                    Process.Start(@"explorer.exe", folderTextBox.Text);
                }
                exitButton_Click(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.ERROR, MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
        private void ScaleToFtp(ScaleClass sc)
        {
            FtpTransferForm form = new FtpTransferForm(_formData, sc);
            if (form.ShowDialog() == DialogResult.OK)
            {
                exitButton_Click(null, null);
            }
        }
        #endregion

        private void getFtpFolderButton_Click(object sender, EventArgs e)
        {
            FtpFolderBrowserDialog form = new FtpFolderBrowserDialog();
            if (form.ShowDialog() == DialogResult.OK)
            {
                _formData.FtpSite = form.FtpUrl;
                _formData.FtpUser = form.FtpUser;
                _formData.FtpPass = form.FtpPassword;
            }
        }




    }
}